from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect
from django.template import loader
from django.shortcuts import render, redirect, reverse
from .models import Question, Choice   # from . import models
# Create your views here.


def index(request):
    latest_question_list = Question.objects.order_by('-id')[:5]
    output = ''
    output += '<html><body><ul>'
    for q in latest_question_list:
        output += '<li>' + q.text + '</li>'
    output += '</ul></body></html>'
    print(output)
    return HttpResponse(output)

def index2(request):
    latest_question_list = Question.objects.order_by('-id')[:5]
    template = loader.get_template('polls/index.html')
    context = {
        'question_list': latest_question_list
    }
    return HttpResponse(template.render(context, request))

def index3(request):
    latest_question_list = Question.objects.order_by('-id')[:5]
    context = {
        'question_list': latest_question_list
    }
    return render(request, 'polls/index.html', context)

def detail(request, question_id):
    print(question_id)
    print(request.GET)
    # print(request.GET['name'])
    try:
        question = Question.objects.get(id=question_id)
    except Exception as e:
        message = 'question id查询不到'
    context = {
        'question': question
    }
    return render(request, 'polls/detail.html', context)


def results(request, question_id):
    """展示投票结果，类似detail页面"""


def vote(request):
    if request.method == 'POST':
        args = request.POST
        # print(args)
        choice_id = args['choice']
        choice_id = int(choice_id)
        selected_choice = Choice.objects.get(id=choice_id)
        selected_choice.votes = selected_choice.votes + 1
        question_id = selected_choice.question.id
        print(selected_choice, selected_choice.text, selected_choice.question.id)
        # return redirect(to='/polls/result')
        print(reverse('polls:results', kwargs={'question_id':question_id}))
        return redirect(to=reverse('polls:results', kwargs={'question_id':question_id}))




